package com.lark.sqlsession;

import com.lark.pojo.Configuration;
import com.lark.pojo.MappedStatment;

import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatment mappedStatment = configuration.getMappedStatmentMap().get(statementId);

        return simpleExecutor.query(configuration, mappedStatment, params);
    }

    @SuppressWarnings(value = "unchecked")
    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {

        List<Object> objects = Optional.ofNullable(selectList(statementId, params)).orElseGet(ArrayList::new);

        return objects.size() > 0 ? (T) objects.get(0) : null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getMapper(Class<T> mapperClass) {
        Object proxy = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 底层都还是去执行JDBC代码 //根据不同情况，来调用selctList或者selectOne
                // 准备参数 1：statmentId :sql语句的唯一标识：namespace.id= 接口全限定名.方法名

                // 获得全限定类型
                String className = method.getDeclaringClass().getName();
                // 获得类型
                String name = method.getName();
                String statementId = className + "." + name;
                // 准备参数2：params:args
                // 获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                // 判断泛型是否参数化
                if (genericReturnType instanceof ParameterizedType) {
                    return selectList(statementId, args);
                } else {
                    return selectOne(statementId, args);
                }
            }
        });
        return (T) proxy;
    }
}
